import router from './router'
import store from './store'
import { getToken } from '@/utils/auth'
import request from "./utils/request";
import {setToken} from "./utils/auth";

const whiteList = ['/login'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // determine whether the user has logged in
  const hasToken = getToken()
  if (hasToken&&hasToken!=='undefined') {
    alert("有token=="+hasToken)
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      //const hasGetUserInfo = store.getters.name
      next()
      // if (hasGetUserInfo) {
      //   next()
      // }
    }
  } else { //前端没有存储token
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    }else{
      let hash = location.href;
      let ticket = '';
      let callbackUrl = window.location.href;
      if(callbackUrl.indexOf('?') !== -1){
        callbackUrl = callbackUrl.substring(0,callbackUrl.indexOf('?'));//http://127.0.0.1:8090/
      }
      if(hash.indexOf('?ticket=')!== -1 ){
        ticket = hash.substring(hash.indexOf('=')+1,hash.length);
        request.get("/login?ticket=" + ticket).then(res => {
           if (res.data.code === 20000) {
             setToken(res.headers.token);
             window.location = callbackUrl //回调执行 刷新当前页面
           }else{
            alert("token无效-->sso跳转到"+process.env.VUE_APP_SS0_LOGIN_URL + callbackUrl)
            window.location = process.env.VUE_APP_SS0_LOGIN_URL + callbackUrl;  //跳转到 https://ssoqxb.iflytek.com:8443/sso/login?service=http://127.0.0.1:8090/
         }
        })
      }else {
        alert("没有ticket-->sso跳转到"+process.env.VUE_APP_SS0_LOGIN_URL + callbackUrl)
        window.location = process.env.VUE_APP_SS0_LOGIN_URL + callbackUrl;
      }
    }
  }
})
router.afterEach(() => { //TODO

})
